package User

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/User"
	"FromNowOnPromote/博客系统/Tblog/redis"
	"encoding/json"
	"strconv"
)

//用户找回密码
type Retrieve struct {
	controllers.MainController
}

type RetrieveData struct {
	Password string `json:"password"`
}

func (this *Retrieve) Post() {
	uuid := this.Ctx.GetCookie("uuid")
	rd := redis.R.Conn
	defer rd.Close()
	uuid, err1 := rd.Get(uuid)
	if uuid == "" || err1 != nil {
		body := map[string]interface{}{"code": 300, "data": "验证失败"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	uuidInt, _ := strconv.Atoi(uuid)
	r := this.Ctx.Request
	decoder := json.NewDecoder(r.Body)
	var ret RetrieveData
	err := decoder.Decode(&ret)
	if err != nil {
		body := map[string]interface{}{"code": 301, "msg": "请求失败"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}

	db := models.ConnDb()
	defer db.Close()
	user := User.TbUser{}
	qerror := db.Where("uuid = ?", uuidInt).Find(&user).Error
	if qerror != nil {
		body := map[string]interface{}{"code": 302, "data": "验证失败", "msg": "用户名不存在"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//修改密码
	e := db.Model(&user).UpdateColumn("password", ret.Password).Error
	if e != nil {
		body := map[string]interface{}{"code": 303, "data": "验证失败", "msg": "系统错误"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	body := map[string]interface{}{"code": 200, "data": "验证成功", "msg": "修改成功"}
	this.Data["json"] = body
	this.ServeJSON()
	return
}
